package com.scwatch.core.web.back.f7;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.scwatch.common.util.Dates;
import com.scwatch.common.web.Servlets;
import com.scwatch.core.constant.Constants;
import com.scwatch.core.domain.Node;
import com.scwatch.core.domain.Special;
import com.scwatch.core.domain.User;
import com.scwatch.core.service.SpecialService;
import com.scwatch.core.support.Context;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * SpecialF7Controller
 * 
 * @author gjl
 * 
 */
@Controller
@RequestMapping("/core/special")
public class SpecialF7Controller {
	@RequestMapping("choose_special_multi.do")
	public String f7NodeTreeMulti(Integer[] ids, HttpServletRequest request, HttpServletResponse response, org.springframework.ui.Model modelMap) {
		Integer siteId = Context.getCurrentSiteId();
		List<Special> list = service.findAll(siteId, null, new PageRequest(0, 2000, Direction.ASC, "id"),0).getContent();
        List<Special> beans = new ArrayList<Special>();
		if (ids != null && ids.length>0) {
			for (Integer id : ids) {
			    if(id!=null){
                    beans.add(service.get(id));
                }
			}
		}

		modelMap.addAttribute("ids", ids);
		modelMap.addAttribute("beans", beans);
		modelMap.addAttribute("list", list);
		Servlets.setNoCacheHeader(response);
		return "core/special/choose_special_multi";
	}

    @RequestMapping("chooseSpec.do")
    public String chooseSpec(HttpServletRequest request, HttpServletResponse response,
                                     org.springframework.ui.Model modelMap) throws IOException {
        return "core/special/choose_spec";
    }

    @RequestMapping("getSpecPage.do")
    @ResponseBody
    public Object getSpecPage(HttpServletRequest request, HttpServletResponse response,
                               @PageableDefault(sort = {"priority", "creationDate"}, direction = Sort.Direction.DESC) Pageable pageable,
                              String title,String startTime,String endTime) throws IOException {
        Integer siteId = Context.getCurrentSiteId();
        Map<String, String[]> params = Servlets.getParamValuesMap(request, Constants.SEARCH_PREFIX);
        params.put("CONTAIN_title",new String[]{title});
        params.put("GTE_creationDate_Date",new String[]{startTime});
        params.put("LTE_creationDate_Date",new String[]{endTime});
        params.put("EQ_level",new String[]{"0"});
        Page<Special> pagelist=service.findAll(siteId,params,pageable,0);
//        String a= JSON.toJSONString(pagelist, SerializerFeature.DisableCircularReferenceDetect);
        List<Special> list=pagelist.getContent();
        JSONArray jsonArray=new JSONArray();
        if(list!=null && list.size()>0){
          JSONObject jsonObject=null;
          for(Special special:list){
              jsonObject =new JSONObject();
              jsonObject.put("id",special.getId());
              jsonObject.put("title",special.getTitle()==null?"":special.getTitle());
              jsonObject.put("categoryName",special.getCategory().getName()==null?"":special.getCategory().getName());
              jsonObject.put("createTime", Dates.formatDate(special.getCreationDate(),"yyyy-MM-dd HH:mm:ss"));
              jsonArray.add(jsonObject);
          }
        }
        JSONObject o=new JSONObject();
        o.put("totalElements",pagelist.getTotalElements());
        o.put("totalPages",pagelist.getTotalPages());
        o.put("content",jsonArray);
        return o;
    }

    @RequestMapping("infochooseSpec.do")
    public String infochooseSpec(HttpServletRequest request, HttpServletResponse response,
                             org.springframework.ui.Model modelMap) throws IOException {
        return "core/special/infochoose_spec";
    }

    @RequestMapping("getInfoSpecPage.do")
    @ResponseBody
    public Object getInfoSpecPage(HttpServletRequest request, HttpServletResponse response,
                              @PageableDefault(sort = {"priority", "creationDate"}, direction = Sort.Direction.DESC) Pageable pageable,
                              Integer parentId,
                              String title,String startTime,String endTime) throws IOException {
        JSONObject o=new JSONObject();
        Integer siteId = Context.getCurrentSiteId();
        User user=Context.getCurrentUser();
        boolean isAllNodePerm=user.getAllNodePerm(siteId);
        if(!isAllNodePerm){
            Set<Node> nodes=user.getNodePerms(siteId);
            boolean haveSpecNode=false;
            for(Node node:nodes){
                if(Constants.SPECIAL_MANAGEMENT.equals(node.getNodeModel().getFlag())){
                    haveSpecNode=true;
                }
            }
            if(!haveSpecNode){
                o.put("totalElements",0);
                o.put("totalPages",0);
                o.put("content",new JSONArray());
                return o;
            }
        }
        Map<String, String[]> params = Servlets.getParamValuesMap(request, Constants.SEARCH_PREFIX);
        params.put("CONTAIN_title",new String[]{title});
        params.put("GTE_creationDate_Date",new String[]{startTime});
        params.put("LTE_creationDate_Date",new String[]{endTime});
        params.put("EQ_level",new String[]{"0"});
        if(parentId!=null){
            params.put("EQ_parent.id",new String[]{parentId.toString()});
            params.put("EQ_level",new String[]{"1"});
        }
        Page<Special> pagelist=service.findAll(siteId,params,pageable,0);
//        String a= JSON.toJSONString(pagelist, SerializerFeature.DisableCircularReferenceDetect);
        List<Special> list=pagelist.getContent();
        JSONArray jsonArray=new JSONArray();
        if(list!=null && list.size()>0){
            JSONObject jsonObject=null;
            for(Special special:list){
                jsonObject =new JSONObject();
                jsonObject.put("id",special.getId());
                jsonObject.put("title",special.getTitle()==null?"":special.getTitle());
                jsonObject.put("categoryName",special.getCategory().getName()==null?"":special.getCategory().getName());
                jsonObject.put("createTime", Dates.formatDate(special.getCreationDate(),"yyyy-MM-dd HH:mm:ss"));
                if(special.getChildren()!=null && special.getChildren().size()>0){
                    jsonObject.put("childs",special.getChildren().size());
                }else{
                    jsonObject.put("childs",0);
                }
                jsonObject.put("level",special.getLevel());
                jsonArray.add(jsonObject);
            }
        }

        o.put("totalElements",pagelist.getTotalElements());
        o.put("totalPages",pagelist.getTotalPages());
        o.put("content",jsonArray);
        return o;
    }

	@Autowired
	private SpecialService service;
}
